package cn.me.alphamq.broker.core.consumequeue;

import cn.me.alphamq.broker.cache.Container;
import cn.me.alphamq.common.model.broker.CommitLogTopicModel;
import cn.me.alphamq.common.model.broker.ConsumeQueueFileModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 给 ConsumeQueue 文件中追加消息索引的处理器
 *
 * @author f
 */
public class ConsumeQueueAppendHandler {

    private ConsumeQueueMMapFileModelManager consumeQueueMMapFileModelManager;

    /**
     * 预映射指定 topic 的所有 ConsumeQueue 文件，提升 MQ 的性能
     *
     * @param topicName
     * @throws IOException
     */
    public void prepareMMapLoading(String topicName) throws IOException {
        CommitLogTopicModel commitLogTopicModel = Container.fetchCommitLogTopicModelByTopic(topicName);
        List<ConsumeQueueFileModel> queueList = commitLogTopicModel.getQueueList();
        List<ConsumeQueueMMapFileModel> consumeQueueMMapFileModelList = new ArrayList<>();
        for (ConsumeQueueFileModel consumeQueueFileModel : queueList) {
            ConsumeQueueMMapFileModel consumeQueueMMapFileModel = new ConsumeQueueMMapFileModel();
            consumeQueueMMapFileModel.loadFileInMMap(topicName, consumeQueueFileModel.getId());
            consumeQueueMMapFileModelList.add(consumeQueueMMapFileModel);
        }
        consumeQueueMMapFileModelManager = Container.getConsumeQueueMMapFileModelManager();
        consumeQueueMMapFileModelManager.put(topicName, consumeQueueMMapFileModelList);
    }

}
